package com.zboin.common.config;

import com.alibaba.cloud.nacos.annotation.NacosConfig;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @author zhboom
 * @date 2025/7/20 21:52
 */
@Configuration
@ConditionalOnClass(RedissonClient.class)
public class RedissonConfig {

    @NacosConfig(group = "DEFAULT_GROUP", dataId = "redis-config", key = "spring.data.redis.password", defaultValue = "123456")
    private String password;

    @NacosConfig(group = "DEFAULT_GROUP", dataId = "redis-config", key = "spring.data.redis.sentinel.master", defaultValue = "mymaster")
    private String master;

    @NacosConfig(group = "DEFAULT_GROUP", dataId = "redis-config", key = "spring.data.redis.sentinel.nodes", defaultValue = "redis://192.168.175.201:26379,redis://192.168.175.202:26379,redis://192.168.175.203:26379")
    private String nodes;

    @NacosConfig(group = "DEFAULT_GROUP", dataId = "redis-config", key = "spring.data.redis.sentinel.password", defaultValue = "123456")
    private String sentinelPassword;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSentinelServers()
                .setPassword(password)
                .setMasterName(master)
                .setSentinelPassword(sentinelPassword)
                .addSentinelAddress(Arrays.stream(nodes.split( ","))
                        .map(node -> "redis://" + node.trim())
                        .toArray(String[]::new))
                .setDatabase(0)
                .setTimeout(5000);

        config.setCodec(StringCodec.INSTANCE);
        config.setCodec(JsonJacksonCodec.INSTANCE);

        return Redisson.create(config);
    }
}
